
//let util = require("../../utils/utils");
let app = getApp();
// t = 0
Page({
    data: {
        stepInfo: {},
        loading: true,
        pointShow: false,
        exchangeSuccess: false,
        loginSuccess: false,
        mapSet: {},
        mapLocation: {},
        pointImg: "",
        anStep: 0,
        mpTitle:"",
        content: "",
        hoorayShow: false,
        exchange_bl: 0,
        exchange_step: 0, //兑换步数
        qingzhuImg: app.resPath + "img/qingzhu.jpg",
        answerId: null,
        currentPointId: null,
        answerShow: false, // 是否显示答题界面 (摘要界面还是答题界面)
    },
    onLoad: function(e) {
        // const query = wx.createSelectorQuery();
        // let m = query.select('#myMap')
        // console.log(m.addMakers)
        this.tMap = wx.createMapContext("myMap");
        this.answerObj = this.selectComponent('#anObj');
        // console.log(this.tMap)
        // console.log(this.data.mapSet)
        this.choujian().then(()=> {
            this.loadData(true);
        });
       //判断操作系统
       let info = wx.getSystemInfoSync();
       this.platform = info.platform;
    },
    t1(e) {
        // console.log(e)
        this.setData({
            mapSet: this.mapsetData
        })
    },
    t2(e) {
        console.log(e)
        //const child = this.selectComponent('#c1');
        // console.log(child.test2())
    },
    choujian(){
        return  new  Promise ( ( resolve, reject ) => {
            wx.request({
                url: app.domain + "ssm/appWebServ/feet/isAward",
                data: {
                    openid: app.openid
                },
                success (res) {
                //console.log('是否中奖',res)
                  if (res.data.respCode=="0"){
                    wx.showModal({
                        title: '提示',
                        content: '恭喜获得随机奖励，答题步数+'+res.data.feetStep,
                        showCancel:false,
                        success (res) {
                        //   if (res.confirm) {
                        //     console.log('用户点击确定')
                        //   } else if (res.cancel) {
                        //     console.log('用户点击取消')
                        //   }
                        }
                      })
                  }
                  resolve();
                },
                fail (e) {
                    resolve();
                }
            })
          })
        
    },
    loadData(first) {
        wx.showLoading({
            title: "加载中..."
        })
        Promise.all([this.getTheStep(), this.getMapData(), this.getConfigInfo(), this.getNodeAnswer()]).then(resArr=> {
            // console.log(resArr)
            //resArr[0].total_km = t;
            //let km = resArr[0].total_km || 0;
            let info = resArr[0];
            this.mapsetData = resArr[1];
            this.showFinish(info, resArr[1], resArr[3]);
            this.checkComplete(resArr[1], resArr[3]);
            //this.checkComplete(km, resArr[1]);
            var o = resArr[0];
            this.setData({
                exchange_bl: resArr[2].exchange_bl,
                exchange_step: resArr[2].exchange_step,
                stepInfo: o,
                mapSet: resArr[1]
            })
            if(first) { //第一次的时候设置坐标和缩放比例 后面再调用 就不设置了
                let loc = {
                    latitude: this.mapsetData.latitude,
                    longitude: this.mapsetData.longitude,
                    scale: this.mapsetData.scale
                }
                this.setData({
                    mapLocation: loc
                })
            }
            wx.hideLoading()
            
        }).catch(e=> {
            // console.log(e)
            wx.showToast({
              title: '操作失败',
            })
            wx.hideLoading() 
        })
    },

    showPointDetail(e) {
     console.log(e)
        //等客户提供文案
        wx.showLoading();
        let n = e.detail.markerId;
        if(n == 99999) {
            n = this.avatarImg.linkId
        }
        else if(n == 99998) {
            console.log(n)
            n = this.toumingMarker.linkId;
        }
        //let p = this.getPointById(n);
        //p.marker.zIndex = -1;
        this.getPointData(n).then(res=>{
            this.setData({
                pointShow: true,
                content: res.content,
                currentPointId: n,
                pointImg:  app.resPath + "json/point/" + n +".jpg",
                mpTitle:res.title,
                anStep: this.getPointById(n).point.steps
            })
            wx.hideLoading();
        }).catch((e)=> {
            wx.hideLoading();
        })
    },
    getPointById(aId) {
        let list = this.mapsetData.markers;
        for(let i = 0; i < list.length; i++) {
            if(list[i].id == aId) {
                return {
                    marker: list[i],
                    point: this.mapsetData.polyline[0].points[i]
                }
            }
        }
        return null;
    },
    resetPointDialog() {
        this.setData({
            currentPointId: null,
            //answerId: null,
            pointShow: false,
            content: "",
            pointImg: "",
            mpTitle:"",
            anStep: 0,
            answerShow: false        
        })
        if(this.answerObj){
            this.answerObj.stopCountADown();
            this.answerObj.stopcountTotalDown();
        }
    },
    showRemainTip() {
        let n = this.data.exchange_step - this.data.stepInfo.total_cur_effect_step;
        wx.showToast({
          title: '还差' + n + "步可兑换",
        })
    },
    mark(mapSet, i) {
        mapSet.markers[i].width = 40;
        mapSet.markers[i].height = 40;
        // mapSet.markers[i].iconPath = user.wxUserInfo.avatarUrl;
        
        mapSet.markers[i].iconPath = app.resPath + "img/finish.png";
        if(i > 0) {
            //mapSet.markers[i-1].iconPath = app.resPath + "img/finish.png";
            mapSet.polyline[0].colorList.unshift("#E1322F")
        }
    },
    getNodeAnswer() {
        return new Promise((rs, rj)=> {
            wx.request({
                url: app.domain + "ssm/appWebServ/answer/getNodeAnswer",
                data: {
                    openid: app.openid
                },
                success (res) {
                  //console.log(res)
                  rs(res.data.list);
                },
                fail (e) {
                    rj(e)
                }
            }) 
        })        
    },
    showFinish(info, mapSet, anNode) {
        let user = app.getUserInfo();
        let last = null;
        let queLength = anNode.length || 0;
        let ex_step = info.total_node_step || 0;
        for(let i= 0; i < mapSet.polyline[0].points.length; i++) {
            let o = mapSet.polyline[0].points[i];
            // 大于标记点 就标记成自己的头像 然后把上一个标记点变成旗子
            if(queLength > i) {
                this.mark(mapSet, i)
            }
            else {
                if(last === null) {
                    last = i;
                }
                // console.log(ex_step, o.steps)
                if(ex_step > o.steps) {
                    if(!this.data.answerId) {
                        this.setData({
                            answerId: mapSet.markers[i].id
                        })
                        this.answerData = {
                            marker: mapSet.markers[i],
                            point: o
                        };
                    }
                    this.mark(mapSet, i);
                    ex_step -= o.steps;
                }
                else {
                    mapSet.markers[i].iconPath = app.resPath + "img/dot.png";
                }

            }
        }
            try {
                if(last === null) {
                    last = mapSet.polyline[0].points.length;  // 如果last是null 说明已经到了最后一个节点
                }
                if(last > 0) {
                    //获取走到的最后一个点
                    let l= mapSet.markers[last-1];
                    //如果有这个对象 说明之前创建过这个头像的点 那就直接把它放到数组里面
                    if(this.avatarImg) {
                        mapSet.markers.push(this.avatarImg);   
                        // console.log(this.avatarImg)
                    }
                    else { // 没有就创建一个
                        let tx = Object.assign({}, l); // 克隆最后一个走过的 
                        tx.iconPath = user.wxUserInfo.avatarUrl; // 头像改一下
                        tx.zIndex = 99999; // zindex改一下
                        tx.id = 99999; // id改一下
                        tx.callout = {};  // 这个对象变成空
                        tx.linkId = l.id;  // 增加一个目前它和那个点是在一起的标记
                        mapSet.markers.push(tx); 
                        this.avatarImg = tx;
                    }
                    // 创建一个透明的点 遮住头像的下一个点 这样就能解决 头像被下一个点覆盖的问题
                    //if(last < mapSet.polyline[0].points.length) {
                        let pre = mapSet.markers[last];
                        let touming = Object.assign({}, pre); 
                        touming.iconPath = "/images/tm.png";
                        touming.zIndex = 99998;
                        touming.id = 99998;
                        touming.linkId = pre.id;
                        mapSet.markers.push(touming); 
                        this.toumingMarker = touming;
                    //}
                    if(this.avatarImg.linkId != l.id) {
                        this.doMove(this.avatarImg, l.id, mapSet);
                        // console.log(mapSet)
                    }
                    //mapSet.markers[last-1].iconPath = user.wxUserInfo.avatarUrl;
                    // console.log(mapSet)
                }
          }catch(e){
            //   console.log(e)
          }
    },
    onStartAnswer() {
        this.setData({
            answerShow: true
        })
        // todo
        let is_last_node = this.answerData.marker.id == this.mapsetData.markers[this.mapsetData.markers.length-3].id ? 1 : 0; // 减2是因为最后两个点是头像点和透明点
        //console.log(this.answerData.marker.id, this.mapsetData.markers[this.mapsetData.markers.length-2].id)
        // console.log(this.data.answerId, this.answerData.point.steps, is_last_node);
        this.answerObj.start({node_id:this.data.answerId, reduce_step:this.answerData.point.steps, is_last_node:is_last_node});
    },
    onAnswerFinish(d) {
        // console.log(d)
        // do request

                
        // then(()=>{
        //     this.answerObj.reset();
        // })
        // this.setData({
        //     answerId: null
        // })
        setTimeout(()=> {
            this.resetPointDialog();
            this.setData({
                answerId: null  //这是answerId为null 下一次loadData的时候 会重新设置
            }, ()=>{
                this.loadData();
            })
        }, 2000)

    },
    doMove(tx, id, mapset) {  // 头像对象 新的最新走到的点的id 
        let arr = mapset.markers;
        let index = this.getIndexById(tx.linkId, arr); // 找到之前头像指向的节点的id的索引
        if(index == -1) {  
            return;
        }
        tx.linkId = id; // 让头像的linkid等于最新点的id
        let list = this.getIncreaseStep(index, id, arr); // 从上次的节点开始找 找到新的节点id 获取他们之间的节点 放到数组里面
        if(!list) {
            list = this.getDecreaseStep(index, id, arr);  // 没找到上面的节点 那就往后找 因为有可能步数兑换规则变了 就会变少
        }
        if(!list) {
            return;
        }
        setTimeout(()=>{
            console.log("move,move")
            this.move(tx, list);

        }, 1100)
    },
    move(tx, list) {
        let l = list.shift();
        // 苹果使用translateMarker 经纬度必须是数字, 安卓使用数字的话 层级就会有问题, 模拟器使用数字也会在控制台报错, 所以这里判断一下,苹果系统才转成数字
        let lon = this.platform == "ios" ? parseFloat(l.longitude) : l.longitude;
        let lat = this.platform == "ios" ? parseFloat(l.latitude) : l.latitude;
        this.tMap.translateMarker({
            markerId: this.avatarImg.id,
            duration: 1000,
            destination: {longitude: lon, latitude:lat},
            complete: ()=> {
                if(list.length) {
                    this.move(tx, list);
                }
                else {
                    tx.longitude = l.longitude;
                    tx.latitude = l.latitude;
                    tx.zIndex = 99999;
                    // console.log(tx, l, this.avatarImg)
                }
            }
        }) 
    },
    //找到增长的节点
    getIncreaseStep(index, id, arr) {
        let list = [];
        for(let i = index; i < arr.length; i++) {
            list.push(arr[i])
            if(arr[i].id == id){
                return list
            }
        }
        return null;
    },
    getDecreaseStep(index, id, arr) {
        let list = [];
        for(let i = index; i >=0; i--) {
            list.push(arr[i])
            if(arr[i].id == id){
                return list
            }
        }
        return null;
    },
    //找到之前的marker所在的index
    getIndexById(id, arr) {
        for(let i = 0; i < arr.length; i++) {
            if(arr[i].id == id) {
                return i
            }
        }
        return -1;
    },
    // checkComplete(km, mapSet) {
    //     let list = mapSet.polyline[0].points;
    //     let n = list[list.length - 1].disAll / 1000;
    //     if(km > n) {
    //         let b = wx.getStorageSync('cz_complete');
    //         if(b != 1) {
    //             this.setData({
    //                 hoorayShow: true
    //             })
    //             wx.setStorage({
    //                 data: 1,
    //                 key: 'cz_complete',
    //             })
    //         }
    //     }
    //     else {
    //         wx.setStorage({
    //           data: 0,
    //           key: 'cz_complete',
    //         })
    //     }
    // },
    checkComplete(mapSet, aNode) {
        console.log(mapSet.polyline[0].points.length, aNode.length)
        if(mapSet.polyline[0].points.length == aNode.length) {
            let b = wx.getStorageSync('cz_complete');
            if(b != 1) {
                this.setData({
                    hoorayShow: true
                })
                wx.setStorage({
                    data: 1,
                    key: 'cz_complete',
                })
            }
        }
        else {
            wx.setStorage({
                data: 0,
                key: 'cz_complete',
              })            
        }
    },
    //比例
    getConfigInfo(e) {
        // return new Promise((rs,rj)=>{
        //     // wx.request({
        //     //     url: app.resPath + "json/config.json",
        //     //     method: "GET",
        //     //     success (res) {
        //     //      // console.log(res)
        //     //      rs(res.data.baseInfo.exchange_bl);
        //     //     },
        //     //     fail (e) {
        //     //         rj(e)
        //     //     }
        //     // })            
            
        // }); 
        return app.getConfig().then(res=>{
            // console.log(res)
            return res.baseInfo
        })

    },

    getPointData(n) {
        return new Promise((rs,rj)=>{
            wx.request({
                url: app.resPath + "json/point/" + n +".json",
                method: "GET",
                success (res) {
                 // console.log(res)
                 rs(res.data);
                },
                fail (e) {
                    rj(e)
                }
            })            
            
        });        
    },
    pointHide() {
        this.setData({
            pointShow: false,
            content: ""
        })
    },
    //获取步数等信息
    getTheStep() {
        return new Promise((rs, rj)=> {
            wx.request({
                url: app.domain + "ssm/appWebServ/feet/getStepInfo",
                data: {
                    openid: app.openid
                },
                success (res) {
                   console.log(res)
                  rs(res.data.stepInfo);
                },
                fail (e) {
                    rj(e)
                }
            }) 
        })
               
    },
    //获取路线信息
    getMapData() {
        return new Promise((rs,rj)=>{
            wx.request({
                url: app.resPath + "json/road.json",
                method: "GET",
                success (res) {
                 // console.log(res)
                 rs(res.data.data);
                },
                fail (e) {
                    rj(e)
                }
            })            
            
        });

    },
    hoorayHide() {
        this.setData({
            hoorayShow: false
        })
    },
    doExchange() {
        // t = 600;
        // this.loadData();
        // return;
        wx.showLoading({
          title: '处理中...',
        })
        wx.request({
            url: app.domain + "/ssm/appWebServ/feet/exchangeStep",
            data: {
                openid: app.openid
            },
            success: (res)=> {
                // console.log(111, res)
                if(res.data.respCode == -1) {
                    wx.showToast({
                        title: res.data.respDesc,
                    })
                    return;                    
                }
                wx.showToast({
                    title: '已兑换',
                })
                this.loadData();
            },
            fail (e) {
               wx.showToast({
                 title: '操作失败',
               })
            },
            complete() {
                wx.hideLoading();
            }
        }) 
    },
    gotoRank() {
        wx.navigateTo({
            url: "/pages/paiming/paiming"
        });
    }
    // previewImage: function() {
    //     wx.previewImage({
    //         urls: [ this.data.roadMapSrc ]
    //     });
    // }

});
